<?php

class Jf_RecordSet implements Iterator, ArrayAccess, Countable {

    private $_container = array();

    private $_iteratorIndex = 0;

    public function __construct ($container) {
        if ( ! empty ($container)) {
            $this -> _container = $container;
        }
    }

    public function key () {
        return key ($this -> _container);
    }

    public function next () {
        $this -> _iteratorIndex ++ ;
        return next ($this -> _container);
    }

    public function rewind () {
        $this -> _iteratorIndex = 0;
        return reset ($this -> _container);
    }

    public function valid () {
        return $this -> _iteratorIndex < $this -> count ();
    }

    public function current () {
        $key = ($this -> _container instanceof Iterator) ? $this -> _container -> key () : key ($this -> _container);
        $row = $this -> _container[$key];
        if (is_array ($row)) {
            $row = new Jf_RecordSet ($row);
        }
        return $row;
    }

    public function __get ($name) {
        return $this -> offsetGet ($name);
    }

    public function offsetSet ($offset, $value) {
        if (is_null ($offset)) {
            $this -> _container[] = $value;
        } else {
            $this -> _container[$offset] = $value;
        }
    }

    public function offsetExists ($offset) {
        return isset ($this -> _container[$offset]);
    }

    public function offsetUnset ($offset) {
        unset ($this -> _container[$offset]);
    }

    public function offsetGet ($offset) {
        $result = isset ($this -> _container[$offset]) ? $this -> _container[$offset] : null;
        if (is_array ($result)) {
            return new Jf_RecordSet ($result);
        } else {
            return $result;
        }
    }

    public function count () {
        return count ($this -> _container);
    }

    public function isEmpty () {
        return $this -> count () ? false : true;
    }

}
